<template>
  <div>
    <h4>第八题</h4>
    <div>
      <span>姓名:</span>
      <input type="text" v-model.lazy="newname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.lazy.number="newage" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="newgender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="TianFn">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0" v-show="obj.length > 0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in obj" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item["name"] }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item["Gender"] }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="xiugai(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      newname: "",
      newage: "",
      newgender: "男",
      xiugaiIndex: null,
      obj: [
        {
          name: "Tom",
          age: 19,
          Gender: "男",
        },
        {
          name: "Jone",
          age: 21,
          Gender: "女",
        },
      ],
    };
  },
  methods: {
    // 添加
    TianFn() {
      const xx = {
        name: this.newname,
        age: this.newage,
        Gender: this.newgender,
      };

      if (this.xiugaiIndex !== null) {
        this.$set(this.obj, this.xiugaiIndex, xx);
        this.xiugaiIndex = null;
      } else {
        this.obj.push(xx);
      }
    },

    del(index) {
      // console.log(index);
      this.obj.splice(index, 1);
    },
    xiugai(index) {
      let x = this.obj[index]; //把编辑的数据取出来
      this.newname = x.name;
      this.newage = x.age;
      this.newgender = x.Gender;
      this.xiugaiIndex = index; //正在编辑的索引值
    },
  },
};
</script>

